/*
 * @Author: yangrongxin
 * @Date: 2021-08-18 15:48:24
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:33:25
 */
import { useState, useEffect } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text, Input } from '@tarojs/components';
import { STORAGE_TYPE } from '@/const/dataDictionary';
// import ArticleItem from '@/pages/PatientEducation/components/ArticleItem';
// import VideoItem from '@/pages/PatientEducation/components/VideoItem';
import RenderItemComponent from '@/pages/PatientEducation/components/RenderItemComponent';
import EvaluationItem from '@/pages/Evaluation/components/EvaluationItem/index';
import { ScrollContent } from '@/components/index';
import { getItemSync, setItemSync } from '@/utils/storage';
import { AtIcon, AtTabs, AtTabsPane } from 'taro-ui';
import { debounce } from 'lodash';
import { getSearchData, getSearchArticleData } from './service';
import styles from './index.module.less';

const tabList = [
  {
    title: '宣教',
  },
  {
    title: '测评',
  },
];

const SearchPage = () => {
  const {
    params: {
      // 0 是宣教 1 是测评
      currentFrom = 0,
    },
  } = useRouter();

  const [current, setCurrent] = useState(Number(currentFrom));
  const [searchValue, setSearchValue] = useState<string>('');
  const [historyList, setHistoryList] = useState<string[]>([]);

  // 获取当前变更的数据
  const getChangeData = (e) => {
    const {
      detail: { value },
    } = e;
    setSearchValue(value);
    if (value.length >= 1) {
      // 从头部插入当前的搜索数据 如果当前数据存在重复 则不进行存储
      const hasIndex = historyList.findIndex((item: string) => item === value);
      if (hasIndex !== -1) return;
      historyList.unshift(value);
      // 每次只存储20条数据
      if (historyList.length > 20) historyList.shift();
      setHistoryList(historyList);
      // 存储当前的列表信息
      setItemSync(STORAGE_TYPE.SEARCHTAGS, historyList);
    }
  };

  /* 清空当前的搜索数据 */
  const clearSearchText = () => {
    setSearchValue('');
  };

  /* 清空所有的历史记录标签 */
  const clearHistoryTags = () => {
    setItemSync(STORAGE_TYPE.SEARCHTAGS, []);
    setHistoryList([]);
  };

  useEffect(() => {
    setHistoryList(getItemSync(STORAGE_TYPE.SEARCHTAGS) || []);
  }, []);

  console.log('historyList', historyList);

  return (
    <View className={styles.container}>
      <View className={styles.containerHeader}>
        {/* 展示搜索的样式 */}
        <View className={styles.searchSection}>
          <AtIcon value="search" size="22" />
          <Input
            placeholder="搜索测评及宣教资讯"
            placeholderClass={styles.inputPlaceholder}
            onInput={debounce(getChangeData, 500)}
            value={searchValue}
          />
          {/* 展示取消按钮 */}
          {searchValue.length !== 0 && <Text onClick={clearSearchText}>取消</Text>}
        </View>
        {/* 当前没有搜索条件的时候 展示历史记录 */}
        {searchValue.length < 1 && (
          <View className={styles.historySection}>
            <View>
              <Text>历史记录</Text>
              <AtIcon value="trash" size="18" onClick={clearHistoryTags} />
            </View>
            <View>
              {historyList.map((item: any, index: number) => {
                return (
                  <View key={String(index)} onClick={() => setSearchValue(item)}>
                    <Text>{item}</Text>
                  </View>
                );
              })}
            </View>
          </View>
        )}
      </View>
      {/* 拥有搜索结果的时候展示对应的列表 */}
      {searchValue.length >= 1 && (
        <View className={styles.searchContent}>
          <AtTabs current={current} swipeable={false} tabList={tabList} onClick={(value) => setCurrent(value)}>
            <AtTabsPane current={current} index={0}>
              <ScrollContent
                onLoadWhenShow
                request={async (data) => {
                  // currentFrom 0 是宣教 1 是测评
                  const listData = await getSearchArticleData(data);
                  const { total } = listData
                  total === 0 && setCurrent(1)
                  // if (
                  //   currentFrom === '0' &&
                  //   listData?.content &&
                  //   (!Array.isArray(listData.content) || listData.content.length === 0)
                  // ) {
                  //   Taro.showToast({
                  //     title: '抱歉未搜索到相关内容',
                  //     icon: 'none',
                  //   });
                  // }
                  return listData;
                }}
                extendScrollContent={styles.extendScrollContent}
                params={{
                  keyword: searchValue,
                }}
                ScrollItem={RenderItemComponent}
              />
            </AtTabsPane>
            <AtTabsPane current={current} index={1}>
              <ScrollContent
                onLoadWhenShow
                request={async (data) => {
                  // currentFrom 0 是宣教 1 是测评
                  const listData = await getSearchData(data);
                  const { total } = listData
                  total === 0 && setCurrent(0)
                  // if (
                  //   currentFrom === '1' &&
                  //   listData?.content &&
                  //   (!Array.isArray(listData.content) || listData.content.length === 0)
                  // ) {
                  //   Taro.showToast({
                  //     title: '抱歉未搜索到相关内容',
                  //     icon: 'none',
                  //   });
                  // }
                  return listData;
                }}
                extendScrollContent={styles.extendScrollContent}
                params={{
                  keyword: searchValue,
                }}
                itemProps={{
                  extendWapperClass: styles.evaluationItemWapper,
                }}
                ScrollItem={EvaluationItem}
              />
            </AtTabsPane>
          </AtTabs>
        </View>
      )}
    </View>
  );
};

export default SearchPage;
